#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <unistd.h>
#include "/usr/include/mosquitto.h"

void message_cb(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg)
{
    printf("收到消息: %s\n", (char *)msg->payload);
}

int main(int argc, char const *argv[])
{
    // 初始化mqtt库
    mosquitto_lib_init();

    // 创建一个mqtt客户端对象
    struct mosquitto *mosq = mosquitto_new(NULL, true, NULL);
    if(mosq == NULL)
    {
        printf("创建mosquitto客户端对象失败\n");
        return -1;
    }

    // 连接mqtt服务器
    int ret = mosquitto_connect(mosq, "120.26.28.32", 1883, 60);
    if(ret != MOSQ_ERR_SUCCESS)
    {
        printf("连接mqtt服务器失败\n");
        return -1;
    }
    else
    {
        printf("连接mqtt服务器成功\n");
    }

    // 订阅主题
    mosquitto_subscribe(mosq, NULL, "text",0);
    printf("订阅主题成功\n");

    // 设置消息回调函数
    mosquitto_message_callback_set(mosq, message_cb);

    // 循环处理网络消息
    mosquitto_loop_forever(mosq, -1, 1);

    return 0;
}